#region imported Namespaces
using System;
using System.EnterpriseServices;
using System.Runtime.InteropServices;
using System.Threading;
using PHSRAG.Utility;
using Humans = PHSRAG.Insight21.Humans;
using Policy = PHSRAG.Insight21.Policy;
using System.Windows.Forms;
using System.Data.SqlClient;
#endregion

namespace PHSRAG.Insight21.HumansFeedWrapper
{
	/// <summary>
	/// The HumansFeedWrapper is a serviced component which allows serialized access to the Humans library. It's
	/// primary (only currently) use is for the new EIRB Protocol feed to call this method when a Process 
	/// (Amendment, Initial review, etc) gets approved in Rex. This is basically a COM+ wrapper to the approve
	/// method, and takes a connectionstring to the database and a processId to be approved as the parameters.
	/// </summary>
	[Guid("0BA4ED7A-08D0-4361-B49B-4C243BDCDD9E")]
	public class HumansFeedWrapper : ServicedComponent
	{
		#region Public Methods
		public void ApproveProcess(string insightConnectionString, string rexConnectionString, int processId)
		{
			Policy.ICachePolicy cachePolicy;
			cachePolicy = new Policy.NullCachePolicy( ); 
			
			Humans.ProtocolProcess process = Humans.ProtocolProcess.GetProtocolProcess( 
				insightConnectionString, 
				processId, 
				cachePolicy , 
				null );
			
			if ( process != null )
			{
				SqlConnection insightConnection = new SqlConnection ( insightConnectionString );
				SqlConnection rexConnection = new SqlConnection ( rexConnectionString );

				SqlTransaction insightTransaction = null;
				SqlTransaction rexTransaction = null;
	            try
				{
					rexConnection.Open();
					rexTransaction = rexConnection.BeginTransaction();

					insightConnection.Open( );
		       		insightTransaction = insightConnection.BeginTransaction( );

					process.Approve( insightTransaction, rexTransaction );

					insightTransaction.Commit();
					rexTransaction.Commit();
				}
				catch ( Exception ex )
				{
					insightTransaction.Rollback();
					rexTransaction.Rollback();

					Utility.ExceptionReport.WriteToEventLog
						("Approving a process failed.",ex,true,Utility.ExceptionReport.ReportType.Error);
				}
				finally
				{
					if ( insightConnection.State != System.Data.ConnectionState.Closed )
						insightConnection.Close( );

					if ( rexConnection.State != System.Data.ConnectionState.Closed )
						rexConnection.Close( );
						
					rexTransaction.Dispose( );
					insightTransaction.Dispose( );
				}

				
			}

		}
		#endregion

	}
}
